/*
 * << Davinci == Copyright (C) 2016 - 2019 EDP == Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and limitations under the
 * License. >>
 *
 */

package com.zwh.csv.apache;

import java.io.*;
import java.util.*;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author doubleZhang
 */
public class CsvUtils {
    private static String fileSuffix = ".csv";

    /**
     * 解析Csv
     *
     * @param csvFile
     * @param charsetName
     * @return
     * @throws ServerException
     */
    public static CsvDataEntity readerWithFirstAsHeader(MultipartFile csvFile, String charsetName)
        throws ServerException {
        if (null == csvFile || !csvFile.getOriginalFilename().toLowerCase().endsWith(fileSuffix)) {
            throw new ServerException("Invalid csv file");
        }

        CsvDataEntity csvDataEntity = null;
        BufferedReader reader = null;
        CSVParser csvParser = null;
        try {
            reader = new BufferedReader(new InputStreamReader(csvFile.getInputStream(), charsetName));
            csvParser =
                new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());

            Set<String> csvHeaders = csvParser.getHeaderMap().keySet();

            List<CSVRecord> records = csvParser.getRecords();
            List<List<String>> values = null;
            List<String> headers = null;

            if (!CollectionUtils.isEmpty(records)) {
                headers = new ArrayList<>();
                for (String key : csvHeaders) {
                    headers.add(key.replace("\uFEFF", ""));
                }
                if (records.size() > 1) {
                    values = new ArrayList<>();
                    for (int i = 1; i < records.size(); i++) {
                        List<String> rowData = new ArrayList<>(headers.size());
                        for (int j = 0; j < csvHeaders.size(); j++) {
                            rowData.add(records.get(i).get(j));
                        }
                        values.add(rowData);
                    }
                }

                csvDataEntity = new CsvDataEntity();
                csvDataEntity.setHeaders(headers);
                csvDataEntity.setValues(values);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServerException(e.getMessage());
        } finally {
            closeCloseable(csvParser);
            closeCloseable(reader);
        }

        return csvDataEntity;
    }

    public static void closeCloseable(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

    /**
     * 写入csv
     *
     * @param filePath
     * @param fileName
     * @param columns
     * @param dataList
     * @return
     * @throws ServerException
     */
    public static String writeCsvWithFirstAsHeader(String filePath, String fileName, List<String> columns,
        List<Map<String, Object>> dataList) throws ServerException {
        String csvFullName = null;
        if (!CollectionUtils.isEmpty(columns)) {
            List<String> headers = new ArrayList<>();
            List<String> headerTypes = new ArrayList<>();
            for (String column : columns) {
                headers.add(column);
            }
            if (!fileName.toLowerCase().endsWith(fileSuffix)) {
                fileName = fileName.trim() + fileSuffix;
            }
            if (!StringUtils.isEmpty(filePath)) {
                File dir = new File(filePath);
                if (!dir.exists() || !dir.isDirectory()) {
                    dir.mkdirs();
                }
            }
            File file = new File(filePath + File.separator + fileName);
            if (file.exists()) {
                fileName = fileName.substring(0, fileName.lastIndexOf(".") - 1) + "_" + UUID.randomUUID() + fileSuffix;
            }
            csvFullName = filePath + File.separator + fileName;
            FileWriter fileWriter = null;
            CSVPrinter csvPrinter = null;
            try {
                CSVFormat csvFormat = CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim();
                fileWriter = new FileWriter(csvFullName, true);
                // 解决csv用excel打开乱码问题
                fileWriter.write("\uFEFF");
                csvPrinter = new CSVPrinter(fileWriter, csvFormat);
                csvPrinter.printRecord(headers);
                csvPrinter.printRecord(headerTypes);

                if (!CollectionUtils.isEmpty(dataList)) {
                    for (Map<String, Object> map : dataList) {
                        List<Object> list = new ArrayList<>();
                        for (String key : headers) {
                            list.add(map.get(key));
                        }
                        csvPrinter.printRecord(list);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new ServerException(e.getMessage());
            } finally {
                flushFlushable(csvPrinter);
                flushFlushable(fileWriter);
                closeCloseable(csvPrinter);
                closeCloseable(fileWriter);
            }
        }
        return csvFullName;
    }

    private static void flushFlushable(Flushable f) {
        if (f != null) {
            try {
                f.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
